import java.sql.*;

public class Connect {
	public static void main(String[] args) {
		Connection conn = null;

		try {
			String userName = "root";
			String password = "root";
			String url = "jdbc:mysql://localhost:3306/db_taxidrivers";
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(url, userName, password);
			System.out.println("Database connection established");

			// select query
			doSelect(conn);
		} catch (Exception e) {
			System.err.println("Cannot connect to database server");
		} finally {
			if (conn != null) {
				try {
					conn.close();
					System.out.println("Database connection terminated");
				} catch (Exception e) { /* ignore close errors */
				}
			}
		}
	}

	private static void doSelect(Connection conn) throws SQLException {
		Statement s = conn.createStatement();
		s.executeQuery("SELECT id, name FROM drivers");
		ResultSet rs = s.getResultSet();
		int count = 0;
		while (rs.next()) {
			int idVal = rs.getInt("id");
			String nameVal = rs.getString("name");
			System.out.println("id = " + idVal + ", name = " + nameVal);
			++count;
		}
		rs.close();
		s.close();
		System.out.println(count + " rows were retrieved");

	}
}